package com.zyf.kafka.producer;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;

/**
 * @author Malegod_xiaofei
 * @create 2024-08-20-21:08
 */
public class KafkaProducerTransactionTest {
    public static void main(String[] args) {

        // 创建配置对象
        Map<String, Object> configMap = new HashMap<>();
        configMap.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        // 对生产的数据 k,v 进行序列化的操作
        configMap.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        configMap.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        configMap.put(ProducerConfig.ACKS_CONFIG, "-1");
        configMap.put(ProducerConfig.ENABLE_IDEMPOTENCE_CONFIG, true);
        configMap.put(ProducerConfig.RETRIES_CONFIG, 5);
        configMap.put(ProducerConfig.BATCH_SIZE_CONFIG, 5);
        configMap.put(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, 3000);
        // 事务id，事务是基于幂等性操作的
        configMap.put(ProducerConfig.TRANSACTIONAL_ID_CONFIG, "my-tx-id");

        // TODO 创建生产者对象
        //     生产者对象需要设置泛型：数据类型的约束
        KafkaProducer<String, String> kafkaProducer = new KafkaProducer<String, String>(configMap);


        // TODO 初始化事务
        kafkaProducer.initTransactions();


        try {
            // TODO 开启事务
            kafkaProducer.beginTransaction();

            for (int i = 0; i < 20; i++) {
                ProducerRecord<String, String> record = new ProducerRecord<String, String>(
                        "test", "key" + i, "value" + i
                );
                Future<RecordMetadata> send = kafkaProducer.send(record);
                System.out.println("发送数据");
            }
            int j = 10 / 0;
            // TODO 生产数据完毕

            // TODO 提交事务
            kafkaProducer.commitTransaction();
        } catch (Exception e) {
            e.printStackTrace();
            // TODO 中止事务
            kafkaProducer.abortTransaction();
        } finally {
            // TODO 关闭生产者对象
            kafkaProducer.close();
        }
    }
}
